除了每一次都把捐獻資訊放進 log 裡面使用 filter 來查詢,我們也可以在 contract 裡面提供簡單的資料結構,讓 contract 本身就能查詢到捐獻者名單,以及他們捐過多少的總額。
本日合約:
pragma solidity ^0.4.25;
contract Donation {
struct DonorInfo {
address[] donors;
mapping (address => uint) ledger;
}
mapping (address => DonorInfo) DonationHistory;
event LogDonate(
address streamer, address donor, string nickname,
uint value, string message);
// 在捐獻的功能裡把觀眾的暱稱&訊息&錢送到 log 上面,永留青史。
function donate(address _streamer, string _nickname, string _message)
public payable {
require(msg.value > 0);
_streamer.transfer(msg.value);
if (DonationHistory[_streamer].ledger[msg.sender] == 0) {
DonationHistory[_streamer].donors.push(msg.sender);
}
DonationHistory[_streamer].ledger[msg.sender] += msg.value;
emit LogDonate(
_streamer,
msg.sender,
_nickname,
msg.value,
_message);
}
function getDonorList() public view returns (address[]) {
return DonationHistory[msg.sender].donors;
}
event LogListDonorInfo(address streamer, address user, uint value);
function listDonorInfo() public {
for (uint i = 0; i < DonationHistory[msg.sender].donors.length; i++) {
address user = DonationHistory[msg.sender].donors[i];
emit LogListDonorInfo(msg.sender, user, DonationHistory[msg.sender].ledger[user]);
}
}
}
本日影片:
https://youtu.be/gOvDqcMGRP4
Smart Contract 實戰教學播放清單:
https://www.youtube.com/playlist?list=PLHmOMPRfmOxSJcrlwyandWYiuP9ZAMYoF